# -*- coding: utf-8 -*-
#!/usr/bin/env python3
# Copyright 2024, David Hu <davidhu@qq.com>
# All rights reserved.

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import NoSuchElementException
import time
import re
import pandas as pd

# 引入对应的动作库
from selenium.webdriver import ActionChains

# 引入对应的选项库
from selenium.webdriver.chrome.options import Options


# 选项定义
# douyin = "//*[@id="field-item-fldOZ3IKOR"]/div/div[2]/div/div/div/div/div/div/div/div[2]/div/div/div/div/li[1]"
# xiaohongshu = "//*[@id="field-item-fldOZ3IKOR"]/div/div[2]/div/div/div/div/div/div/div/div[2]/div/div/div/div/li[2]"
# jinritoutiao = "//*[@id="field-item-fldOZ3IKOR"]/div/div[2]/div/div/div/div/div/div/div/div[2]/div/div/div/div/li[3]"
# weibo ="//*[@id="field-item-fldOZ3IKOR"]/div/div[2]/div/div/div/div/div/div/div/div[2]/div/div/div/div/li[5]"

# 27号："/html/body/div[1]/div/div[1]/div[3]/div/div[3]/form/div[2]/div/div[2]/div/div/div/div/div/div/div[1]/div[2]/div/div/div/div/div[2]/div[2]/div[4]/div[13]/div[3]/div/div"
# 25号："/html/body/div[1]/div/div[1]/div[3]/div/div[3]/form/div[2]/div/div[2]/div/div/div/div/div/div/div[1]/div[2]/div/div/div/div/div[2]/div[2]/div[4]/div[9]/div[3]/div/div"


# 使用正则表达式匹配URL
def extract_url(text: str) -> str:
    """
    从文本中提取URL。
    参数:text (str): 待提取的文本。
    返回:str: 提取出的URL。
    """
    url = re.findall(
        r"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+", text
    )
    return url


def get_element(driver, locator, time=60):
    """
    说明：获取指定的元素
    参数:
        locator: 元素定位器
        driver: 浏览器驱动
        time: 等待时间
    """
    try:
        element = WebDriverWait(driver, time).until(EC.presence_of_element_located(locator))
    except NoSuchElementException:
        print("没有找到元素")
        element = None
    return element


# 点击空白区域使失去焦点
def click_blank(driver):
    form_title = driver.find_element(By.CLASS_NAME, "form-title")
    form_title.click()


def auto_input_form(
    url_content: str,
    submit_end_sleep_time: int,
) -> None:
    """
    自动向表单填写数据。

    参数:
    url_content (str): 填写的url内容。
    submit_end_sleep_time (int): 提交前的等待时间。

    返回:
    None
    """

    # 设置Chrome浏览器驱动程序的路径
    chrome_driver_path = r"C:\chromedriver-win64\chromedriver.exe"

    # 创建一个Service对象，并传递ChromeDriver的路径
    service = Service(chrome_driver_path)

    # 设置Chrome浏览器选项
    chrome_options = Options()
    # 添加用户代理,应对反爬虫机制
    user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36"
    chrome_options.add_argument(f"user-agent={user_agent}")

    # 初始化Chrome浏览器
    browser_driver = webdriver.Chrome(service=service, options=chrome_options)

    # 定义要打开网页
    my_web_url = "https://sgmw.feishu.cn/share/base/form/shrcnx63J3kpKzcfvsYfWroVspc"

    # 打开网页
    browser_driver.get(my_web_url)

    # 等待几秒
    time.sleep(1)

    # 通过id定位元素

    yuangongbianhao_element = get_element(browser_driver, (By.ID, "field-item-fldOZ3IKOR"))

    # 向输入框发送数据
    yuangongbianhao_element.send_keys("21860060")
    # 向日期框输入数据

    # 等待几秒
    time.sleep(3)
    # 点击title，实现鼠标取消聚焦
    click_blank(browser_driver)

    # 找到日期框
    date_element = get_element(
        browser_driver,
        (
            By.XPATH,
            "/html/body/div[1]/div/div[1]/div[3]/div/div[3]/form/div[2]/div/div[2]/div/div/div/div/div/div",
        ),
    )

    date_element.click()

    # 找到日期框选择日期
    date_day_element = get_element(
        browser_driver,
        (
            By.XPATH,
            "/html/body/div[1]/div/div[1]/div[3]/div/div[3]/form/div[2]/div/div[2]/div/div/div/div/div/div/div[1]/div[2]/div/div/div/div/div[2]/div[2]/div[4]/div[9]/div[3]/div/div",
        ),
    )
    date_day_element.click()

    # 点击title，实现鼠标取消聚焦
    click_blank(browser_driver)
    # 找到平台选项框
    platform_element = get_element(
        browser_driver,
        (
            By.XPATH,
            "/html/body/div[1]/div/div[1]/div[3]/div/div[3]/form/div[3]/div/div[2]/div/div/div/div/div/div/div",
        ),
    )
    platform_element.click()

    # 选择选项
    select_element = get_element(
        browser_driver,
        (
            By.XPATH,
            '//*[@id="field-item-fldOZ3IKOR"]/div/div[2]/div/div/div/div/div/div/div/div[2]/div/div/div/div/li[5]',
        ),
    )

    select_element.click()

    # 填写链接
    url_element = get_element(
        browser_driver,
        (
            By.XPATH,
            "/html/body/div[1]/div/div[1]/div[3]/div/div[3]/form/div[4]/div/div[2]/div/div/div/div/div/div/div/div/div/div[1]/div/div",
        ),
    )

    url_element.send_keys(extract_url(url_content))
    # 点击title，实现鼠标取消聚焦
    click_blank(browser_driver)

    # 点击提交
    submit_element = get_element(
        browser_driver,
        (
            By.XPATH,
            "/html/body/div[1]/div/div[1]/div[3]/div/div[3]/form/div[9]/div/div/div/button",
        ),
    )

    time.sleep(submit_end_sleep_time)

    submit_element.click()

    # 等待几秒
    time.sleep(1)
    browser_driver.quit()


# 读取excel文件，遍历其中的数据，运行自动填写函数
def my_function():
    # 读取 Excel 文件
    df = pd.read_excel(r"./url_content2.xlsx", sheet_name="Sheet2", engine="openpyxl")

    # 假设你的数据在 'Column1' 这一列中，你可以遍历这一列的所有行
    for index, row in df.iterrows():
        content = row["微博"]  # 替换 'Column1' 为你的实际列名
        auto_input_form(content, 5)


if __name__ == "__main__":
    # 这里是主程序逻辑
    my_function()
